<template>
  <el-card>
    <el-input v-model="roleName" disabled />
    <el-tree
      class="role-tree"
      :data="RoleList"
     show-checkbox
     :props="{
        children: 'children',
        label: 'name',
      }"
      default-expand-all
      node-key="id"
      ref="treeRef"
    />
    <el-button type="primary" @click="assignRolePermission">确定</el-button>
    <el-button @click="cancel">取消</el-button>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "RoleAuth",
};
</script>

<script lang="ts" setup>
import { onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import {getRolePermissionListApi,assignRolePermissionApi} from "@/api/acl/permission"
import type { PermissionList } from "@/api/acl/model/permissionModel";
import { ElMessage } from "element-plus";

const route=useRoute()
const RoleList=ref<PermissionList>([])
const  roleName=route.query.roleName as string
const roleId=route.query.id as string
const treeRef=ref()
onMounted(async()=>{
const res= await  getRolePermissionListApi(roleId)
console.log(res)
RoleList.value=res.children
const ids=getSelectedIds(res.children)
treeRef.value.setCheckedKeys(ids);

})
const getSelectedIds=(RoleList:PermissionList)=>{
  let ids:string[]=[]
  RoleList.forEach((role)=>{
    if(role.children && role.children.length){
      const childrenIds=getSelectedIds(role.children)
      ids=[...ids,...childrenIds]
    }else{
      if(role.select){
        ids.push(role.id)
      }
    }
  })
  return ids;

}
const router=useRouter()
const cancel=()=>{
  router.push({
    name:"role"
  })
}
const assignRolePermission=()=>{
  const checkedKeys = treeRef.value.getCheckedKeys();
  const halfCheckedKeys = treeRef.value.getHalfCheckedKeys();
  assignRolePermissionApi(roleId,[ ...checkedKeys, ...halfCheckedKeys,])
  ElMessage.success("分配角色权限成功");
  cancel()
}

</script>

<style scoped>
.role-tree {
  margin: 10px 0;
}
</style>
